<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>检测历史记录</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/viewerjs/1.11.3/viewer.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root {
            --primary-color: #e62227;
            --secondary-color: #f8981d;
            --background-color: #f8f9fa;
            --card-background: #ffffff;
            --text-color: #333;
            --light-text-color: #6c757d;
            --border-color: #dee2e6;
            --shadow: 0 4px 15px rgba(0, 0, 0, 0.07);
            --delete-color: #dc3545;
            /* 新增删除按钮颜色变量 */
            --view-color: #007bff;
            /* 新增查看按钮颜色变量 */
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            margin: 0;
            background-color: var(--background-color);
            color: var(--text-color);
        }

        .top-nav {
            background-color: var(--card-background);
            box-shadow: var(--shadow);
            padding: 0 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 70px;
        }

        .logo {
            max-height: 40px;
        }

        .nav-menu {
            display: flex;
            gap: 25px;
        }

        .nav-link {
            color: var(--text-color);
            text-decoration: none;
            font-size: 16px;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 8px;
            transition: all 0.3s ease;
            position: relative;
        }

        .nav-link:hover,
        .nav-link.active {
            background-color: rgba(230, 34, 39, 0.1);
            color: var(--primary-color);
        }

        .container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 40px;
            background: var(--card-background);
            border-radius: 16px;
            box-shadow: var(--shadow);
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            /* Allow items to wrap on smaller screens */
            gap: 15px;
            /* Space between items */
        }

        .search-box {
            display: flex;
            gap: 5px;
        }

        .search-box input[type="text"] {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-size: 16px;
            width: 200px;
            /* Adjust width as needed */
        }

        .search-box button {
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .footer-toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }

        .delete-btn {
            background-color: var(--primary-color);
            /* 统一为主题色 */
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .delete-btn:hover {
            background-color: #c51a1f;
            /* 统一为主题色的hover效果 */
        }

        .per-page-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .history-table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
        }

        .history-table th,
        .history-table td {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }

        .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .btn {
            display: inline-block;
            padding: 8px 16px;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            transition: background-color 0.3s;
            border: none;
            text-align: center;
        }

        .btn-view {
            background-color: var(--view-color);
        }

        .btn-view:hover {
            background-color: #0056b3;
        }

        .btn-delete {
            background-color: var(--delete-color);
        }

        .btn-delete:hover {
            background-color: #c82333;
        }

        .history-table th {
            font-weight: 600;
            background-color: #f8f9fa;
        }

        .history-table tbody tr:hover {
            background-color: #f1f1f1;
        }

        .thumbnail {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }

        .pagination a {
            color: var(--primary-color);
            padding: 8px 16px;
            text-decoration: none;
            transition: background-color .3s;
            border: 1px solid #ddd;
            margin: 0 4px;
        }

        .pagination a.active {
            background-color: var(--primary-color);
            color: white;
            border: 1px solid var(--primary-color);
        }

        .pagination a:hover:not(.active) {
            background-color: #ddd;
        }

        @media (max-width: 768px) {
            .top-nav {
                padding: 0 20px;
                height: 60px;
            }

            .nav-menu {
                gap: 10px;
            }

            .nav-link {
                font-size: 14px;
                padding: 8px 10px;
            }

            .nav-link i {
                display: none;
            }

            .container {
                padding: 20px;
                margin: 20px auto;
            }

            .history-table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
        }

        @media (max-width: 480px) {
            .nav-link {
                font-size: 13px;
                padding: 6px 8px;
            }
        }
    </style>
</head>

<body>
    {% include '_nav.html' %}
    <div class="container">
        <h1>检测历史记录</h1>

        <div class="toolbar">
            <button id="bulk-delete-btn" class="delete-btn">删除选中</button>
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索图片名称..."
                    value="{{ search_query if search_query else '' }}">
                <button id="search-button" class="btn btn-view">搜索</button>
            </div>
            <a href="{{ url_for('export_history') }}" class="btn btn-view">导出Excel</a>
        </div>

        <table class="history-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>ID</th>
                    <th>缩略图</th>
                    <th>图片名称</th>
                    <th>检测时间</th>
                    <th>健力宝数量</th>
                    <th>层数</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="history-images">
                {% for record in records.items %}
                <tr>
                    <td><input type="checkbox" class="record-checkbox" value="{{ record.id }}"></td>
                    <td>{{ record.id }}</td>
                    <td><img src="{{ url_for('uploaded_file', filename=record.annotated_image_path.split('/')[-1]) }}"
                            data-original="{{ url_for('uploaded_file', filename=record.annotated_image_path.split('/')[-1]) }}"
                            class="thumbnail"></td>
                    <td><a href="{{ url_for('uploaded_file', filename=record.image_path.split('/')[-1]) }}"
                            target="_blank" rel="noopener noreferrer">{{ record.image_path.split('/')[-1] }}</a></td>
                    <td>{{ record.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}</td>

                    <td>{{ record.sku_count }}</td> <!-- 显示SKU总数 -->
                    <td>{{ record.layer_count }}</td>
                    <td>
                        <div class="action-buttons">
                            <a href="{{ url_for('history_detail', record_id=record.id) }}" class="btn btn-view">查看</a>
                            <a href="#" class="btn btn-delete"
                                onclick="deleteSingleRecord({{ record.id }}); return false;">删除</a>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>

        <div class="footer-toolbar">
            <div class="pagination">
                {% set pagination_args = {'per_page': per_page, 'search': search_query} %}
                {% if records.has_prev %}
                <a href="{{ url_for('history', page=records.prev_num, **pagination_args) }}">&laquo;</a>
                {% endif %}
                {% for page_num in records.iter_pages() %}
                {% if page_num %}
                <a href="{{ url_for('history', page=page_num, **pagination_args) }}"
                    class="{{ 'active' if page_num == records.page else '' }}">{{ page_num }}</a>
                {% else %}
                ...
                {% endif %}
                {% endfor %}
                {% if records.has_next %}
                <a href="{{ url_for('history', page=records.next_num, **pagination_args) }}">&raquo;</a>
                {% endif %}
            </div>
            <div class="page-jump">
                <span>跳转到:</span>
                <input type="number" id="page-input" value="{{ records.page }}" min="1" max="{{ records.pages }}">
                <button onclick="jumpToPage()" class="btn btn-view">Go</button>
            </div>
            <div class="per-page-selector">
                <span>每页显示:</span>
                <select id="per-page" onchange="changePageAndPerPage()">
                    <option value="10" {% if per_page==10 %}selected{% endif %}>10</option>
                    <option value="20" {% if per_page==20 %}selected{% endif %}>20</option>
                    <option value="50" {% if per_page==50 %}selected{% endif %}>50</option>
                    <option value="100" {% if per_page==100 %}selected{% endif %}>100</option>
                </select>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/viewerjs/1.11.3/viewer.min.js"></script>
    <script>
        const gallery = new Viewer(document.getElementById('history-images'));

        function getBaseUrl() {
            const url = new URL(window.location.href);
            // Remove page, per_page, and search parameters to get a clean base URL
            url.searchParams.delete('page');
            url.searchParams.delete('per_page');
            url.searchParams.delete('search');
            return url;
        }

        function changePageAndPerPage() {
            const perPage = document.getElementById('per-page').value;
            const url = getBaseUrl();
            url.searchParams.set('per_page', perPage);
            url.searchParams.set('page', 1); // Reset to first page when changing per_page
            const searchInput = document.getElementById('search-input').value;
            if (searchInput) {
                url.searchParams.set('search', searchInput);
            }
            window.location.href = url.toString();
        }

        function jumpToPage() {
            let page = parseInt(document.getElementById('page-input').value);
            const maxPage = parseInt(document.getElementById('page-input').max);
            if (isNaN(page) || page < 1) {
                page = 1;
            } else if (page > maxPage) {
                page = maxPage;
            }

            const url = getBaseUrl();
            url.searchParams.set('page', page);
            const perPage = document.getElementById('per-page').value;
            url.searchParams.set('per_page', perPage);
            const searchInput = document.getElementById('search-input').value;
            if (searchInput) {
                url.searchParams.set('search', searchInput);
            }
            window.location.href = url.toString();
        }

        document.getElementById('search-button').addEventListener('click', () => {
            const searchInput = document.getElementById('search-input').value;
            const url = new URL(window.location.href);
            if (searchInput) {
                url.searchParams.set('search', searchInput);
            } else {
                url.searchParams.delete('search');
            }
            url.searchParams.set('page', 1); // Reset to first page on search
            window.location.href = url.toString();
        });

        document.getElementById('search-input').addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                document.getElementById('search-button').click();
            }
        });

        function deleteRecords(ids) {
            if (!confirm(`确定要删除选中的 ${ids.length} 条记录吗？`)) {
                return;
            }

            fetch("{{ url_for('delete_records') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ ids: ids }),
            }).then(response => response.json()).then(data => {
                if (data.success) {
                    window.location.reload();
                } else {
                    alert('删除失败: ' + data.message);
                }
            }).catch((error) => {
                console.error('Error:', error);
                alert('删除时发生错误');
            });
        }

        function deleteSingleRecord(id) {
            deleteRecords([id]);
        }

        document.getElementById('bulk-delete-btn').addEventListener('click', () => {
            const selectedIds = Array.from(document.querySelectorAll('.record-checkbox:checked')).map(cb => parseInt(cb.value));
            if (selectedIds.length === 0) {
                alert('请至少选择一条记录');
                return;
            }
            deleteRecords(selectedIds);
        });

        document.getElementById('select-all').addEventListener('change', (event) => {
            document.querySelectorAll('.record-checkbox').forEach(checkbox => {
                checkbox.checked = event.target.checked;
            });
        });
    </script>
</body>

</html>